<!--
 * @Author: Lqq
 * @Date: 2025-07-08 12:24:45
 * @LastEditors: Lqq 46081704@qq.com
 * @LastEditTime: 2025-08-04 10:28:08
 * @FilePath: \questionnaire\src\views\FillSurvey.vue
 * @Description: 
 * 
 * Copyright (c) 2025 by ${git_name_email}, All Rights Reserved. 
-->
<template v-if="isReady">
  <!-- <div class="p-4"> -->
  <div class="container">
    <el-page-header content="填写问卷" @back="goBack" />

    <!-- 元数据字段 -->
    <div class="survey-invitation">
      <!-- 顶部蓝色标题栏 -->
      <div class="section-title">以下内容由调查员填写</div>
      <div class="survey-content">
        <div class="section-subtitle">本次调研地址</div>
        <div class="form-grid">
          <div class="input-with-label">
            <el-input v-model="province" disabled />
            <span class="suffix-label">省（自治区、直辖市）</span>
          </div>
          <div class="input-with-label">
            <el-input v-model="city" disabled />
            <span class="suffix-label">市</span>
          </div>
          <div class="input-with-label">
            <el-select v-model="newQuestions.fields.monitoringPointNumber.answer" placeholder="请选择县（市、区）" @change="handleCountyChange">
              <el-option v-for="item in countiesOptions" :key="item.code" :label="item.name" :value="item.code" />
            </el-select>
            <span class="suffix-label">县（市、区）</span>
          </div>

          <div class="input-with-label">
            <el-select v-model="newQuestions.fields.townNumber.answer" placeholder="请选择街道（乡镇）" @change="handleStreetChange">
              <el-option v-for="item in streetOptions" :key="item.code" :label="item.name" :value="item.code" />
            </el-select>
            <span class="suffix-label">街道（乡镇）</span>
          </div>

          <div class="input-with-label">
            <el-select v-model="newQuestions.fields.villageNumber.answer" placeholder="请选择居委员会（村）" @change="handleVillageChange">
              <el-option v-for="item in villageOptions" :key="item.code" :label="item.name" :value="item.code" />
            </el-select>
            <span class="suffix-label">居委员会（村）</span>
          </div>

          <div class="input-with-label">
            <el-select v-model="newQuestions.fields.familyNumber.answer" placeholder="请选择家庭户">
              <el-option v-for="item in householdOptions" :key="item.code" :label="item.name" :value="item.code" />
            </el-select>
            <span class="suffix-label">家庭户</span>
          </div>

          <!-- 选中家庭户后显示地址 -->
          <div class="input-with-label">
            <el-input :value="selectedHouseholdAddress" disabled />
            <span class="suffix-label">家庭户地址</span>
          </div>
        </div>

        <div class="row">
          <!-- 问卷编码 -->
          <div class="card code-section">
            <div class="card-title">问卷编码</div>
            <div class="code-inputs">
              <h1>{{ newQuestions.fields.monitoringPointNumber.answer }} -</h1>
              <h1>{{ townNumber }} -</h1>
              <h1>{{ villageNumber }} -</h1>
              <h1>{{ newQuestions.fields.familyNumber.answer }}</h1>
            </div>
          </div>

          <!-- KISH码 -->
          <div class="card kish-section">
            <div class="card-title">KISH码</div>
            <div class="kish-code">
              <span class="kish-text">{{ newQuestions.fields.G02.answer }}</span>
            </div>
          </div>

          <!-- 负责人 -->
          <div class="card info-section">
            <div class="card-title">负责人</div>
            <div class="form-grid">
              <div class="form-row1">
                <span class="suffix-label">调查员</span>
                <el-input
                  v-model="newQuestions.metadata.investigator.answer"
                  @input="(val) => (newQuestions.metadata.investigator.answer = val.replace(/[^\u4e00-\u9fa5]/g, ''))"
                />
              </div>
              <div class="form-row1">
                <span class="suffix-label">调查日期</span>
                <!-- <el-input v-model="newQuestions.metadata.surveyDate.answer" /> -->
                <el-date-picker
                  v-model="newQuestions.metadata.surveyDate.answer"
                  type="date"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  placeholder="选择日期"
                  :editable="false"
                  class="date-picker"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 人员信息表 -->
    <div class="survey-table">
      <!-- 标题栏 -->
      <div class="section-title">以下内容由调查员填写</div>
      <div class="table-container">
        <div class="left">
          <div class="card-title"><span style="color: red">15～69岁</span>家庭成员登记表</div>
          <div class="table-child">
            <el-table :data="newQuestions.fields.G03.answer" style="width: 100%" border>
              <el-table-column label="姓名" align="center">
                <template #default="scope">
                  <el-input v-model="scope.row.name" @input="(val) => (scope.row.name = val.replace(/[^\u4e00-\u9fa5]/g, ''))" />
                </template>
              </el-table-column>
              <el-table-column label="性别" align="center">
                <template #default="scope">
                  <el-select v-model="scope.row.gender" placeholder="请选择性别">
                    <el-option label="男" value="1"></el-option>
                    <el-option label="女" value="2"></el-option>
                  </el-select>
                </template>
              </el-table-column>
              <el-table-column label="年龄" align="center">
                <template #default="scope">
                  <el-input v-model="scope.row.age" :maxlength="3" @input="(val) => (scope.row.age = val.replace(/[^\d]/g, ''))" />
                </template>
              </el-table-column>
              <el-table-column label="成员编号" align="center">
                <template #default="scope">
                  <el-input v-model="scope.row.code" @input="(val) => (scope.row.code = val.replace(/[^\d]/g, ''))" disabled />
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center">
                <template #default="scope">
                  <el-button @click="removeRow(scope.$index)" type="danger" size="small">删除 </el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-button @click="addRow" type="primary" class="mt-2" style="margin-top: 10px">添加成员 </el-button>
          </div>
        </div>
        <div class="right">
          <div class="right-top">
            <div class="card-title">样本确定</div>
            <div class="table-child">
              <div class="right-question">
                <div style="margin-bottom: 10px">
                  <span>G01. 15～69岁家庭成员人数： </span>
                  <strong style="font-size: 20px">{{ newQuestions.fields.G01.answer }}</strong>
                </div>
                <div style="margin-bottom: 10px">
                  <span>G02. KISH码确定的调查对象：</span>
                  <strong style="font-size: 20px; color: red">{{ respondent }}</strong>
                </div>
              </div>
            </div>
          </div>
          <div class="right-bottom">
            <p class="note">填写家庭成员登记表、抽取调查对象的方法</p>
            <ul class="guide">
              <li>1. 只填写<span style="color: red; font-weight: 600">15～69岁</span>常住人口</li>
              <li>2. 先填男性，按照年龄从大到小顺序</li>
              <li>3. 再填女性，按照年龄从大到小顺序</li>
              <li>4. 给表格中的家庭成员顺序编号</li>
              <li>5. 根据分配的KISH表代码，找到KISH表指示的家庭成员</li>
              <li>6. 对抽中的调查对象进行问卷调查</li>
            </ul>
          </div>
        </div>
      </div>
    </div>

    <!-- 基础字段 -->
    <div class="survey-form">
      <!-- 标题栏 -->
      <div class="section-title">以下内容由受访者自己/调查员协助完成</div>
      <div class="survey-content">
        <!-- 问候语 -->
        <div class="greeting">
          您好！国家卫生健康委正在开展全国居民健康素养调查，调查结果是评价全国居民健康素养水平、
          制定健康相关政策的重要依据。您被选中参加本次调查，您的参与对我们非常重要，回答的内容将会被严格保密， 不会对个人产生任何不利影响。
        </div>

        <!-- 第二行：负责人 + 问卷填写人 -->
        <div class="row">
          <!-- 负责人 -->
          <div class="card fill-section">
            <div class="card-title">问卷完成情况</div>
            <RadioWithSub
              style="margin-left: 20px"
              v-model="newQuestions.metadata.finishMethod.answer"
              :options="newQuestions.metadata.finishMethod.options"
            />
          </div>

          <!-- 问卷填写人 -->
          <!-- <div class="card person-section">
            <div class="card-title">如果您愿意参加本次调查，请点击下方按钮</div>
            <div class="form-pairs">
              <el-button type="primary" :class="{ 'is-active': isSelected }" @click="isSelected = true">确认参与</el-button>
              <div class="pair">
                <span>与受访人合影</span>
                <PhotoUpload v-model="newQuestions.metadata.photo.answer" />
              </div>

              <div class="pair">
                             保留位置，今后这里可以添加签名功能
                <el-button type="primary" @click="submitSurvey">确认参与</el-button>
              </div>
            </div>
          </div> -->
        </div>
      </div>
    </div>

    <!-- 问答部分 -->
    <div class="questions-container">
      <el-form ref="formRef" :model="newQuestions" label-width="140px" v-if="isReady">
        <!-- 问卷章节 -->
        <div v-for="(section, sectionIndex) in newQuestions.sections" :key="section.title">
          <div class="title">{{ section.title }}</div>
          <h4 class="text-lg font-semibold sec-title" v-if="section.secTitle">{{ section.secTitle }}</h4>
          <div style="padding: 0 40px">
            <div class="text-lg font-semibold thi-title" v-if="section.thiTitle">
              {{ section.thiTitle }}
            </div>
          </div>

          <div v-if="sectionIndex != 6" class="section-cartain">
            <div v-for="(q, questionIndex) in section.questions" :key="q.id" class="mb-4 section-content" v-show="showQuestion(q.id)">
              <div class="font-medium text-base mb-1 section-content-title">
                <span v-if="q.required" style="color: red; margin-right: 4px">*</span>{{ q.id }}.
                {{ q.label }}
                <img :src="q.image" alt="" style="width: 30px; height: 30px" v-if="q.image" />
              </div>

              <el-form-item
                :prop="`sections[${sectionIndex}].questions[${questionIndex}].answer`"
                label-width="20px"
                :rules="
                  shouldValidate(q)
                    ? [
                        {
                          required: true,
                          message: '请选择 ' + q.label,
                          trigger: ['change', 'blur']
                        }
                      ]
                    : []
                "
                class="m-0"
              >
                <component
                  :is="getComponent(q.type)"
                  v-model="q.answer"
                  v-bind="getProps(q)"
                  class="vertical-group"
                  @change="() => triggerFieldValidate(sectionIndex, questionIndex)"
                />
              </el-form-item>
            </div>
          </div>
        </div>
      </el-form>
    </div>
    <div class="mt-4 flex gap-2 footer-buttons">
      <el-button type="primary" @click="handleSave">保存问卷</el-button>
      <el-button @click="goBack">关闭</el-button>
    </div>
    <div class="ending">调查到此结束，感谢您的支持与配合！</div>

    <el-dialog title="保存成功" v-model="dialogVisible" width="30%">
      <span>感谢配合，点击“确认”按钮保存问卷！</span>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="close">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { computed, nextTick, onMounted, reactive, ref, watch } from "vue"
import { useRoute, useRouter } from "vue-router"
import { ElDatePicker, ElInput, ElMessage } from "element-plus"
import { getSurveyById, saveSurvey } from "@/db/localDb"
import { useAutoSave } from "@/composables/useAutoSave"
import PhotoUpload from "@/components/PhotoUpload.vue"
import RadioWithSub from "@/components/RadioWithSubInput.vue"
import CheckboxWithSub from "@/components/CheckboxWithSubInput.vue"
import JudgeQuestion from "@/components/JudgeQuestion.vue"
import { getKishPeople, generateUUID } from "./utils"

const componentMap: Record<string, any> = {
  input: ElInput,
  date: ElDatePicker,
  month: ElDatePicker,
  radio: RadioWithSub,
  checkbox: CheckboxWithSub,
  judge: JudgeQuestion,
  photo: PhotoUpload
}

const getComponent = (type: string) => componentMap[type] || ElInput

const getProps = (item: any) => {
  const base: any = {}

  if (item.type === "date") {
    base.type = "date"
    base.placeholder = "请选择日期"
    base.editable = false
    base.style = { width: "180px" }
  }
  if (item.type === "month") {
    base.type = "month"
    base.placeholder = "请选择年月"
    base.style = { width: "180px", marginTop: "10px" }
    base.format = "YYYY/MM"
    base.editable = false
    base.valueFormat = "YYYY/MM"
  }

  if (["judge", "radio", "checkbox"].includes(item.type)) {
    base.options = Array.isArray(item.options) ? item.options : [] // ✅ 保证 options 始终为数组
  }
  return base
}

const route = useRoute()
const router = useRouter()
const template = ref({ title: "", fileNamePattern: "", fields: {}, metadata: {}, sections: [] })
const dialogVisible = ref(false)
const formRef = ref()
const submitted = ref(false)
const isSelected = ref(false)
const draftId = (route.query.id as string) || generateUUID()
const title = computed(() => {
  const fields = newQuestions.fields || {}
  const mp = fields.monitoringPointNumber?.answer || ""
  const town = fields.townNumber?.answer || ""
  const village = fields.villageNumber?.answer || ""
  const family = fields.familyNumber?.answer || ""
  return mp && town && village && family ? `${mp}-${town}-${village}-${family}-${householder.value}` : `-`
})
const householder = ref("")

const isReady = ref(false)

let newQuestions = reactive<Record<string, any>>({
  fields: {
    monitoringPointNumber: { answer: "" },
    townNumber: { answer: "" },
    villageNumber: { answer: "" },
    familyNumber: { answer: "", inputs: null },
    G01: { answer: "" },
    G02: { answer: "", options: [] },
    G03: { answer: [] }
  },
  metadata: {
    photo: "",
    respondent: { answer: "" },
    investigator: { answer: "" },
    surveyDate: { answer: "" },
    finishMethod: {
      answer: "",
      type: "radio",
      options: [
        {
          label: "自填完成",
          value: "1"
        },
        {
          label: "因文化程度低，面对面调查",
          value: "2"
        },
        {
          label: "因其他原因，面对面调查",
          value: "3",
          izSub: true,
          subTitle: "请注明原因："
        }
      ]
    }
  },
  sections: []
})

//增加问卷计时器
const timer = ref(0)
const timerInterval = setInterval(() => {
  timer.value++
  // console.log("timer.value", timer.value)
}, 1000)

const oldTime = ref(0)

const totalTime = computed(() => {
  return timer.value + oldTime.value
})

useAutoSave(draftId, newQuestions, isReady, { title, totalTime })

//打开新页面是加载默认问卷并初始化答案
const loadTemplate = async () => {
  const res = await fetch("/health-literacy-2025.json")
  template.value = JSON.parse(JSON.stringify(await res.json()))
  console.log("template.value", template.value)
  let fields = JSON.parse(JSON.stringify(template.value.fields))
  let metadata = JSON.parse(JSON.stringify(template.value.metadata))
  let sections = JSON.parse(JSON.stringify(template.value.sections))

  Object.assign(newQuestions, {
    title: template.value.title,
    fileNamePattern: template.value.fileNamePattern,
    fields,
    metadata,
    sections
  })
  Object.keys(newQuestions.fields).forEach((f) => {
    newQuestions.fields[f].answer = newQuestions.fields[f].type === "table" ? [] : ""
  })

  Object.keys(newQuestions.metadata).forEach((k) => {
    newQuestions.metadata[k].answer = ""
  })

  newQuestions.sections.forEach((s: any) => {
    s.questions.forEach((q: any) => {
      q.answer = q.type === "checkbox" ? [] : ""
    })
  })

  isReady.value = true

  await nextTick() // 🟢 等待 DOM 挂载和响应系统建立
  addRow()

  formRef.value?.clearValidate() // 🟢 清除初始化前遗留的校验状态（可选）

  console.log("newQuestions", newQuestions)
}

onMounted(async () => {
  await getCounties()

  let id = route.query.id as string
  console.log("id", id)
  if (id) {
    let questions = await getSurveyById(id)
    console.log("questions", questions)
    oldTime.value = questions.workingTime
    let savedQuestions = JSON.parse(JSON.stringify(questions.quesData))
    if (questions) {
      Object.assign(newQuestions, savedQuestions)
      console.log("newQuestions2222", newQuestions)
    }
    isReady.value = true
  } else {
    await loadTemplate()
  }
})

const showQuestion = (id: string) => {
  let show = true
  if (id === "F14" && newQuestions.sections[5]?.questions[12]?.answer.includes("1")) {
    newQuestions.sections[5].questions[13].answer=''
    show = false
  }
  if (id === "F17" && newQuestions.sections[5]?.questions[15]?.answer.includes("1")) {
    newQuestions.sections[5].questions[16].answer=''
    show = false
  }
  if (id === "E8" && newQuestions.sections[4]?.questions[6]?.answer.includes("1")) {
    newQuestions.sections[4].questions[7].answer=[]
    show = false
  }
  return show
}

const province = ref("四川")
const city = ref("宜宾")
const countiesOptions = ref<Option[]>([])
const streetOptions = ref<Option[]>([])
const villageOptions = ref<Option[]>([])
const householdOptions = ref<Option[]>([])

const areaData = ref<CountyType[]>([]) // ← 存整份四级数据
//获取四级完整数据
const getCounties = async () => {
  const res = await fetch("/four_level_data_7560.json")
  const data = (await res.json()) as CountyType[]
  areaData.value = data
  // 把县列表直接映射成 { code, name } 数组
  countiesOptions.value = mapOpts(areaData.value)
}

// 计算当前选中家庭户的地址
const selectedHouseholdAddress = computed(() => {
  const countyCode = newQuestions.fields.monitoringPointNumber.answer
  const streetCode = newQuestions.fields.townNumber.answer
  const villageCode = newQuestions.fields.villageNumber.answer
  const householdCode = newQuestions.fields.familyNumber.answer

  // 依次查找到对应对象
  const county = filterByCode(areaData.value, countyCode)
  const street = county && filterByCode(county.children, streetCode)
  const village = street && filterByCode(street.children, villageCode)
  const household = village && filterByCode(village.children, householdCode)
  return household?.address || ""
})

// 县(一级) 选中
watch(
  () => newQuestions.fields.monitoringPointNumber.answer,
  (code) => {
    console.log("1111111111111")
    const county = filterByCode(areaData.value, code)
    streetOptions.value = county ? mapOpts(county.children) : []
    // villageOptions.value = [];
    // householdOptions.value = [];
    // newQuestions.fields.townNumber.answer = '';
    // newQuestions.fields.villageNumber.answer = '';
    // newQuestions.fields.familyNumber.answer = '';
  },
  { immediate: true }
)

const handleCountyChange = () => {
  villageOptions.value = []
  householdOptions.value = []
  newQuestions.fields.townNumber.answer = ""
  newQuestions.fields.villageNumber.answer = ""
  newQuestions.fields.familyNumber.answer = ""
}

// 街道(二级) 选中后
watch(
  () => newQuestions.fields.townNumber.answer,
  (code) => {
    const county = filterByCode(areaData.value, newQuestions.fields.monitoringPointNumber.answer)
    const street = county && filterByCode(county.children, code)
    villageOptions.value = street ? mapOpts(street.children) : []
    // householdOptions.value = [];
    // newQuestions.fields.villageNumber.answer = '';
    // newQuestions.fields.familyNumber.answer = '';
  },
  { immediate: true }
)
const handleStreetChange = () => {
  householdOptions.value = []
  newQuestions.fields.villageNumber.answer = ""
  newQuestions.fields.familyNumber.answer = ""
}

// 居委会(三级) 选中后：
watch(
  () => newQuestions.fields.villageNumber.answer,
  (code) => {
    const county = filterByCode(areaData.value, newQuestions.fields.monitoringPointNumber.answer)
    const street = county && filterByCode(county.children, newQuestions.fields.townNumber.answer)
    const village = street && filterByCode(street.children, code)
    householdOptions.value = village ? mapOpts(village.children) : []
    // newQuestions.fields.familyNumber.answer = '';
  },
  { immediate: true }
)
const handleVillageChange = () => {
  newQuestions.fields.familyNumber.answer = ""
}

// 监听住户变化用于获取KISH码：
watch(
  () => newQuestions.fields.familyNumber.answer,
  (code) => {
    console.log("12345674", areaData.value)
    const county = filterByCode(areaData.value, newQuestions.fields.monitoringPointNumber.answer)
    const street = county && filterByCode(county.children, newQuestions.fields.townNumber.answer)
    const village = street && filterByCode(street.children, newQuestions.fields.villageNumber.answer)
    const household = village && filterByCode(village.children, newQuestions.fields.familyNumber.answer)
    newQuestions.fields.G02.answer = household?.kish || ""
    householder.value = household?.name || ""
  },
  { immediate: true }
)
const getoptionsImmediate = () => {}

function filterByCode<T extends { code: string }>(list: T[], code: string): T | undefined {
  return list.find((item) => item.code === code)
}

function mapOpts<T extends { code: string; name: string }>(list: T[]): Option[] {
  return list.map(({ code, name }) => ({ code, name }))
}

const townNumber = computed(() => {
  if (!newQuestions.fields.townNumber.answer) return ""
  const extractedString = newQuestions.fields.townNumber.answer.split("-").pop()
  return extractedString
})

const villageNumber = computed(() => {
  if (!newQuestions.fields.villageNumber.answer) return ""
  const extractedString = newQuestions.fields.villageNumber.answer.split("-").pop()
  return extractedString
})

//人员列表增加一行数据
const addRow = () => {
  const hasIncomplete = newQuestions.fields.G03.answer.some((item: any) => {
    return item.name === "" || item.gender === "" || item.age === ""
  })

  if (hasIncomplete) {
    ElMessage({
      type: "error",
      message: "请填写完整之前的家庭成员信息后再添加新成员"
    })
    return
  }

  newQuestions.fields.G03.answer.push({
    name: "",
    gender: "",
    age: "",
    code: newQuestions.fields.G03.answer.length + 1
  })
}

//人员列表移除一行数据
const removeRow = (index: number) => {
  newQuestions.fields.G03.answer.splice(index, 1)
  // 重新编号
  newQuestions.fields.G03.answer.forEach((m, i) => (m.code = String(i + 1)))
}

//监听家庭人员列表变化，以确定被访人
const respondent = ref("")
watch(
  () => newQuestions.fields.G03.answer,
  async (newVal, oldVal) => {
    // 你可以在这里执行任何副作用，比如重新计算、校验等
    if (newVal.length > 0) {
      let tableCode = newVal[newVal.length - 1].code
      newQuestions.fields.G01.answer = tableCode
      let peopleCode = await getKishPeople(newQuestions.fields.G01.answer, newQuestions.fields.G02.answer)
      newQuestions.fields.G03.answer.forEach((item: any) => {
        if (item.code == peopleCode) {
          newQuestions.metadata.respondent.answer = item.name
          respondent.value = item.name
        }
      })
    }
  },
  { deep: true } // 关键点：深度监听对象或数组的内部变化
)

const submitSurvey = () => {
  newQuestions.metadata.respondent.answer = respondent.value
}
const shouldValidate = (q: any) => {
  return submitted.value && q.required
}

const handleSave = () => {
  //基础信息的手动校验
  const fieldErrors = validateFields()
  if (fieldErrors.length > 0) {
    ElMessage.error(fieldErrors[0]) // 只提示第一个错误
    return
  }

  //元数据部分手动校验
  const metadataErrors = validateMetadata()
  if (metadataErrors.length > 0) {
    ElMessage.error(metadataErrors[0]) // 只提示第一个错误
    return
  }

  //问题表单部分的校验
  submitted.value = true
  nextTick(() => {
    console.log("formRef", formRef.value)
    formRef.value.validate(async (valid: boolean, invalidFields) => {
      if (!valid) {
        const firstInvalidPath = Object.keys(invalidFields)[0]

        // 替换 path 中的 answer 为 id
        const idPath = firstInvalidPath.replace(/\.answer$/, ".id")

        // 工具函数：安全获取深层属性
        const getDeepProp = (obj: any, path: string) => {
          const pathArray = path.replace(/\[(\d+)\]/g, ".$1").split(".")
          return pathArray.reduce((acc, key) => (acc && acc[key] != null ? acc[key] : null), obj)
        }
        //获取为填项的id
        const fieldId = getDeepProp(newQuestions, idPath) || "未知字段"

        ElMessage.error(` “${fieldId}”题必填项未填写，请完成填写！`)
        return
      }
      // const time = totalTime
      try {
        let saveTitle =
          newQuestions.fields.monitoringPointNumber.answer +
          "-" +
          newQuestions.fields.townNumber.answer +
          "-" +
          newQuestions.fields.villageNumber.answer +
          "-" +
          newQuestions.fields.familyNumber.answer +
          "-" +
          householder.value
        await saveSurvey({
          id: draftId,
          workingTime: totalTime.value,
          respondent: newQuestions.metadata.respondent.answer,
          investigators: newQuestions.metadata.investigator.answer,
          investigationDate: newQuestions.metadata.surveyDate.answer,
          // household: household,
          quesNumber:
            newQuestions.fields.monitoringPointNumber.answer +
            "-" +
            newQuestions.fields.townNumber.answer +
            "-" +
            newQuestions.fields.villageNumber.answer +
            "-" +
            newQuestions.fields.familyNumber.answer,
          areaCode:
            newQuestions.fields.monitoringPointNumber.answer +
            "-" +
            newQuestions.fields.townNumber.answer +
            "-" +
            newQuestions.fields.villageNumber.answer,
          title: saveTitle,
          fileName: saveTitle,
          quesData: JSON.parse(JSON.stringify(newQuestions)),
          updatedAt: Date.now()
        })
        dialogVisible.value = true
      } catch (e: any) {
        ElMessage.error("保存失败: " + e.message)
      }
    })
  })
}
const triggerFieldValidate = (si: number, qi: number) => {
  const path = `sections[${si}].questions[${qi}].answer`
  nextTick(() => {
    formRef.value?.validateField(path)
  })
}

//基础信息校验
function validateFields(): string[] {
  const errors: string[] = []

  Object.entries(newQuestions.fields).forEach(([key, field]: any) => {
    const val = field.answer

    if (
      field.required &&
      (val === undefined || val === null || (typeof val === "string" && val.trim() === "") || (Array.isArray(val) && val.length === 0))
    ) {
      errors.push(`请输入“${field.label}”`)
    } else if (field.pattern && !field.pattern.test(val)) {
      errors.push(`“${field.label}”格式不正确`)
    }
  })

  return errors
}

//基础信息校验
function validateMetadata(): string[] {
  const errors: string[] = []

  Object.entries(newQuestions.metadata).forEach(([key, metadata]: any) => {
    const val = metadata.answer

    if (
      metadata.required &&
      (val === undefined || val === null || (typeof val === "string" && val.trim() === "") || (Array.isArray(val) && val.length === 0))
    ) {
      errors.push(`请输入“${metadata.label}”`)
    } else if (metadata.pattern && !metadata.pattern.test(val)) {
      errors.push(`“${metadata.label}”格式不正确`)
    }
  })

  return errors
}

const goBack = () => router.push("/list")
const close = () => {
  dialogVisible.value = false
  nextTick(() => {
    goBack()
  })
}
</script>

<style scoped>
.container {
  width: 97vw;
  height: 100vh;
  padding: 10px;
  position: relative;
}

.title {
  background-color: rgb(72, 116, 203);
  color: #fff;
  padding: 8px 12px;
  font-weight: bold;
}

.section-cartain {
  padding: 5px 20px;
}

.section-content {
  /* padding: 5px 20px; */
  border: 1px solid #ccc;
  margin-top: 5px;
}

/* 问卷题目部分 */
.questions-container {
  background: #fff;
  padding: 10px;
  font-size: 16px;
}

.section-content-title {
  background-color: #a7c3e7;
  padding: 5px 20px;
}

.sec-title {
  margin-left: 20px;
}

.thi-title {
  /* width: 80%; */
  padding: 10px;
  border: 1px solid #ccc;
}

.vertical-group {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  margin-top: 10px;
  gap: 4px;
}

.survey-form {
  background: #fff;
  padding: 10px;
  font-size: 16px;
  /* font-family: 'Microsoft YaHei', sans-serif;
  font-size: 14px;
  padding: 10px;
  color: #333; */
}

.survey-content {
  padding: 20px;
}

.row {
  display: flex;
  margin-top: 12px;
  gap: 10px;
}

/* 问卷编码区域 */
.code-section {
  /* flex: 6; */
  width: 40%;
}

.info-section {
  /* flex: 3; */
  /* 宽度为30%再减去10px */
  width: calc(45% - 10px);
  /* font-size: 13px; */
  /* padding: 10px; */
  /* border: 1px solid #ddd; */
  /* height: 100%; */
  /* box-sizing: border-box; */
}

.card {
  border: 1px solid #ccc;
  /* padding: 10px; */
  box-sizing: border-box;
  background-color: #fff;
}

.card-title {
  background-color: #a7c3e7;
  font-weight: bold;
  padding: 4px 8px;
  margin-bottom: 10px;
  font-size: 14px;
}

.code-inputs {
  display: flex;
  /* justify-content: space-between; */
  padding: 10px;
  align-items: flex-end;
  gap: 12px;
  margin-left: 10px;
}

/* 第二行 */
.person-section {
  /* flex: 6; */
  width: 50%;
}

.fill-section {
  /* flex: 4; */
  width: 100%;
}

.form-pairs {
  display: flex;
  align-items: flex-start; /* 默认各行顶端对齐 */
  padding: 10px;
  gap: 12px;
}

.pair {
  display: flex;
  align-items: center;
  gap: 10px;
}

.pair span {
  white-space: nowrap;
  width: 100px;
  text-align: right;
}
.pair:last-child {
  margin-left: auto;
  align-self: flex-end;
}
.radio-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-bottom: 4px;
}

/* 元数据CSS */

.survey-invitation {
  background: #fff;
  padding: 10px;
  font-size: 16px;
}

.survey-content {
  padding: 20px;
}

.section-title {
  background-color: rgb(72, 116, 203);
  color: white;
  padding: 8px 12px;
  font-weight: bold;
}

.greeting {
  margin: 16px 0;
  line-height: 1.6;
  color: #333;
  font-weight: 600;
}

.section-subtitle {
  background-color: #d0def3;
  padding: 8px 12px;
  font-weight: bold;
  margin: 20px 0 16px;
  color: #333;
}

.form-row {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 20px;
}

.form-row1 {
  display: flex;
  align-items: center;
  gap: 20px;
}

.date-picker {
  width: 100%;
}

.form-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 20px;
}

.input-with-label {
  display: flex;
  align-items: center;
  width: 350px;
}

.input-with-label .el-input {
  flex: 1;
}

.suffix-label {
  margin-left: 8px;
  white-space: nowrap;
  font-size: 14px;
  color: #444;
}

.thanks {
  font-size: 15px;
  color: #333;
}

/* 人员信息部分的样式开始 */
.survey-table {
  background: #fff;
  padding: 10px;
  font-size: 16px;
}

.table-container {
  display: flex;
  padding: 20px;
  gap: 10px;
}

.left {
  border: 1px solid #ccc;
  /* flex: 0 0 60%; */
  background: #f9f9f9;
  box-shadow: 2px 2px 8px rgba(0, 0, 0, 0.1);
  width: 65%;
}

.right {
  /* flex: 1; */
  background: #f9f9f9;
  box-shadow: 2px 2px 8px rgba(0, 0, 0, 0.1);
  width: calc(35% - 10px);
}

.right-top {
  border: 1px solid #ccc;
}

.right-bottom {
  padding: 5px;
}

.table-child {
  padding: 8px 12px;
}

.right-question {
  margin-left: 20px;
}

.kish-section {
  /* flex: 1; */
  display: flex;
  width: 15%;
  flex-direction: column;
}

.kish-code {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.kish-text {
  font-size: 32px;
  color: red;
  font-weight: bold;
}

.guide {
  margin-top: 16px;
  padding-left: 18px;
  font-size: 13px;
  line-height: 1.6;
  color: #333;
}

.note {
  font-size: 12px;
  color: #888;
  margin-top: 6px;
}

/* 人员信息部分的样式结束 */
.is-active {
  background-color: rgb(51, 126, 204) !important; /* 选中状态的背景色 */
  color: white !important; /* 选中状态的文字颜色 */
  /* 可以添加其他样式 */
}
.footer-buttons {
  margin-left: 20px;
}
.ending {
  padding: 20px 10%;
  font-size: 25px;
  font-weight: 600;
  color: #333;
}
.dialog-footer {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
